<template>
  <div class="weather-container">
    <!-- 区域选择 -->
    <el-cascader
      v-model="selectedDistrict"
      :options="districtOptions"
      :props="cascaderProps"
      placeholder="请选择地区"
      class="district-select"
      clearable
      @change="handleDistrictChange"
    />

    <!-- 内容标签页 -->
    <el-tabs v-model="activeTab" class="weather-tabs">
      <el-tab-pane label="实时天气" name="current">
        <el-row :gutter="20">
          <el-col :span="14">
            <current-weather
              :weather-data="weatherData?.now"
              :district-name="selectedDistrictName"
              :update-time="updateTime"
            />
          </el-col>
          <el-col :span="10">
            <div class="weather-info-cards">
              <div class="info-card">
                <div class="card-header">
                  <i class="el-icon-info"></i>
                  <span>天气提示</span>
                </div>
                <div class="card-content">
                  <el-alert
                    :title="getWeatherTips(weatherData?.now?.text || '')"
                    type="info"
                    :closable="false"
                    show-icon
                  />
                </div>
              </div>

              <div class="info-card">
                <div class="card-header">
                  <i class="el-icon-data-line"></i>
                  <span>温度变化</span>
                </div>
                <div class="card-content temp-trend">
                  <div class="trend-item">
                    <div class="label">今日温度区间</div>
                    <div class="value">
                      {{ weatherData?.forecasts?.[0]?.low }}° ~
                      {{ weatherData?.forecasts?.[0]?.high }}°
                    </div>
                  </div>
                  <el-divider direction="vertical" />
                  <div class="trend-item">
                    <div class="label">明日温度区间</div>
                    <div class="value">
                      {{ weatherData?.forecasts?.[1]?.low }}° ~
                      {{ weatherData?.forecasts?.[1]?.high }}°
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </el-col>
        </el-row>
      </el-tab-pane>

      <el-tab-pane label="天气预报" name="forecast">
        <weather-forecast :forecasts="weatherData?.forecasts" :area="selectedDistrictName" />
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from "vue";
import { getWeatherData } from "@/apis/Weather.js";
import CurrentWeather from "./components/CurrentWeather.vue";
import WeatherForecast from "./components/WeatherForecast.vue";

interface WeatherData {
  location: {
    country: string;
    province: string;
    city: string;
    name: string;
    id: string;
  };

  now: {
    temp: number;
    feels_like: number;
    rh: number;
    wind_class: string;
    wind_dir: string;
    text: string;
    uptime: string;
  };

  forecasts: Array<{
    date: string;
    week: string;
    high: number;
    low: number;
    wc_day: string;
    wc_night: string;
    wd_day: string;
    wd_night: string;
    text_day: string;
    text_night: string;
  }>;
}

interface District {
  name: string;
  code: string;
}

interface CascaderOption {
  value: string;
  label: string;
  children?: CascaderOption[];
}

// 级联选择器的选项数据
const districtOptions: CascaderOption[] = [
  {
    value: "420100",
    label: "武汉市",
    children: [
      { value: "420102", label: "江岸区" },
      { value: "420103", label: "江汉区" },
      { value: "420104", label: "硚口区" },
      { value: "420105", label: "汉阳区" },
      { value: "420106", label: "武昌区" },
      { value: "420107", label: "青山区" },
      { value: "420111", label: "洪山区" },
      { value: "420112", label: "东西湖区" },
      { value: "420113", label: "汉南区" },
      { value: "420114", label: "蔡甸区" },
      { value: "420115", label: "江夏区" },
      { value: "420116", label: "黄陂区" },
      { value: "420117", label: "新洲区" },
    ],
  },
];

// 级联选择器的配置
const cascaderProps = {
  expandTrigger: "hover" as const,
  checkStrictly: true, // 允许选择任意一级
  value: "value",
  label: "label",
};

const selectedDistrict = ref(["420100"]); // 默认选择武汉市整体
const selectedDistrictName = computed(() => {
  if (!selectedDistrict.value || selectedDistrict.value.length === 0) {
    return "武汉市"; // 当清空选择时，默认显示武汉市
  }
  // 如果选择了区，显示区名，否则显示武汉市
  const districtCode = selectedDistrict.value[selectedDistrict.value.length - 1];
  if (districtCode === "420100") {
    return "武汉市";
  }
  const district = districtOptions[0].children?.find((d) => d.value === districtCode);
  return district?.label || "未知地区";
});

const updateTime = ref("");
const weatherData = ref<WeatherData | null>(null);
const activeTab = ref("current");

// 处理区域变化
const handleDistrictChange = () => {
  // 如果清空选择，默认查询武汉市
  const districtCode =
    selectedDistrict.value && selectedDistrict.value.length > 0
      ? selectedDistrict.value[selectedDistrict.value.length - 1]
      : "420100";

  fetchAllWeatherData(districtCode);
};

// 获取天气数据
const fetchAllWeatherData = async (districtCode: string = "420100") => {
  try {
    const { data, success } = await getWeatherData({
      district_id: districtCode,
      data_type: "all",
    });

    if (success) {
      weatherData.value = data.result;
      updateTime.value = new Date().toLocaleString();
    }
  } catch (error) {
    console.error("获取天气数据失败:", error);
  }
};

// 获取天气提示
const getWeatherTips = (text: string) => {
  const tipsMap: Record<string, string> = {
    晴: "天气晴朗，适合外出活动，注意防晒。",
    多云: "天气较好，但云量较多，紫外线较弱。",
    阴: "天气阴沉，紫外线较弱，适合户外活动。",
    小雨: "有小雨，出门请带伞，道路可能湿滑。",
    中雨: "降雨量较大，出行注意防雨，驾驶需谨慎。",
    大雨: "降雨量大，尽量避免外出，注意交通安全。",
    雪: "天气寒冷，路面可能结冰，出行注意防滑。",
    雾: "能见度较低，出行注意安全。",
    霾: "空气质量较差，外出需注意防护。",
    风: "风力较大，出行注意防风。",
    雷: "雷暴天气，尽量避免外出。",
    冰雹: "冰雹天气，尽量避免外出。",
    霜: "霜冻天气，尽量避免外出。",
    雾霾: "空气质量较差，外出需注意防护。",
  };
  return tipsMap[text] || "天气变化莫测，出行请注意安全。";
};

onMounted(() => {
  fetchAllWeatherData("420100");
});
</script>

<style lang="scss" scoped>
.weather-container {
  .district-select {
    width: 300px;
    margin-bottom: 20px;
  }

  .weather-info-cards {
    height: 100%;
    display: flex;
    flex-direction: column;
    gap: 20px;

    .info-card {
      flex: 1;
      background-color: #fff;
      border-radius: 10px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
      transition: all 0.3s ease;
      overflow: hidden;

      &:hover {
        box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
      }

      .card-header {
        padding: 15px 20px;
        background: linear-gradient(135deg, #409eff 0%, #1e88e5 100%);
        color: white;
        font-weight: bold;
        display: flex;
        align-items: center;
        gap: 8px;

        i {
          font-size: 18px;
        }
      }

      .card-content {
        padding: 20px;
        background-color: rgba(255, 255, 255, 0.8);
        backdrop-filter: blur(10px);
      }

      .tips {
        :deep(.el-alert) {
          margin: 0;
          border: none;
          background-color: rgba(255, 255, 255, 0.6);
          border-radius: 8px;

          .el-alert__title {
            font-size: 14px;
            color: #606266;
            line-height: 1.6;
          }
        }
      }

      .temp-trend {
        display: flex;
        justify-content: space-around;
        align-items: center;
        height: calc(100% - 60px);

        .trend-item {
          text-align: center;
          display: flex;
          flex-direction: column;
          justify-content: center;
          gap: 15px;

          .label {
            color: #909399;
            font-size: 14px;
            opacity: 0.8;
          }

          .value {
            color: #409eff;
            font-size: 24px;
            font-weight: bold;
            text-shadow: 0 1px 2px rgba(64, 158, 255, 0.2);
            letter-spacing: 1px;
          }
        }

        :deep(.el-divider--vertical) {
          height: 50px;
          margin: 0 20px;
          border-color: rgba(64, 158, 255, 0.2);
        }
      }
    }
  }
}
</style>
